<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<%@ include file="/WEB-INF/jsp/common/css.jsp"%>
<style>
.tree li {
	list-style-type: none;
	cursor: pointer;
}

table tbody tr:nth-child(odd) {
	background: #F4F4F4;
}

table tbody td:nth-child(even) {
	color: #C00;
}
</style>
</head>

<body>
	<!-- 顶部栏，经常改变，需要重新编译，动态包含 -->
	<jsp:include page="/WEB-INF/jsp/common/top.jsp"></jsp:include>


	<div class="container-fluid">
		<div class="row">
			<!-- 侧面菜单栏 -->
			<jsp:include page="/WEB-INF/jsp/common/sidebar.jsp"></jsp:include>
			<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
				<div class="panel panel-default">
					<div class="panel-heading">
						<h3 class="panel-title">
							<i class="glyphicon glyphicon-th"></i> 数据列表
						</h3>
					</div>
					<div class="panel-body">
						<form class="form-inline" role="form" style="float: left;">
							<div class="form-group has-feedback">
								<div class="input-group">
									<div class="input-group-addon">查询条件</div>
									<input id="condition" class="form-control has-success"
										type="text" placeholder="请输入查询条件">
								</div>
							</div>
							<button id="queryBtn" type="button" class="btn btn-warning">
								<i class="glyphicon glyphicon-search"></i> 查询
							</button>
						</form>
						<button type="button" class="btn btn-danger"
							style="float: right; margin-left: 10px;">
							<i class=" glyphicon glyphicon-remove"></i> 删除
						</button>
						<security:authorize access="hasRole('PM - 项目经理')">
							<button type="button" class="btn btn-primary"
								style="float: right;" onclick="showAddModal()">
								<i class="glyphicon glyphicon-plus"></i> 新增
							</button>
						</security:authorize>
						<br>
						<hr style="clear: both;">
						<div class="table-responsive">
							<table id="contentTable" class="table table-bordered">
								<thead>
									<tr>
										<th width="30">#</th>
										<th width="30"><input type="checkbox"></th>
										<th>名称</th>
										<th width="100">操作</th>
									</tr>
								</thead>
								<tbody>

								</tbody>
								<tfoot>
									<tr>
										<td colspan="6" align="center">
											<ul class="pagination">
											</ul>
										</td>
									</tr>

								</tfoot>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	
	<!-- 添加模态框 -->
	<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="myModalLabel">添加角色</h4>
	      </div>
	      <div class="modal-body">
	        <div class="form-group">
			  <label for="addModalRoleName">角色名称</label>
			  <input type="text" class="form-control" name="name" id="addModalRoleName" placeholder="请输入角色名称">
		    </div>
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
	        <button id="saveBtn" type="button" class="btn btn-primary">添加</button>
	      </div>
	    </div>
	  </div>
	</div>
	
	<!-- 修改模态框 -->
	<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="myModalLabel">修改角色</h4>
	      </div>
	      <div class="modal-body">
	        <div class="form-group">
	          <input type="hidden" name="id" value="">
			  <label for="updateModalRoleName">角色名称</label>
			  <input type="text" class="form-control" name="name" id="updateModalRoleName" placeholder="请输入角色名称">
		    </div>
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
	        <button id="updateBtn" type="button" class="btn btn-primary">修改</button>
	      </div>
	    </div>
	  </div>
	</div>
	
	<!-- 分配权限模态框 -->
	<div class="modal fade" id="assignModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-header">
	        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
	        <h4 class="modal-title" id="myModalLabel">分配权限</h4>
	      </div>
	      <div class="modal-body">
	        <ul id="treeDemo" class="ztree"></ul>
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
	        <button id="assignBtn" type="button" class="btn btn-primary">确定</button>
	      </div>
	    </div>
	  </div>
	</div>

	<%@ include file="/WEB-INF/jsp/common/js.jsp"%>
	<script type="text/javascript">
		//页面加载完后的事件处理
		$(function() {
			$(".list-group-item").click(function() {
				if ($(this).find("ul")) {
					$(this).toggleClass("tree-closed");
					if ($(this).hasClass("tree-closed")) {
						$("ul", this).hide("fast");
					} else {
						$("ul", this).show("fast");
					}
				}
			});
			initData(1);
		});

		var json = {
			pageNum : 1,
			pageSize : 10
		};

		function initData(pageNum) {
			json.pageNum = pageNum;
			var index = -1;
			//发起ajax请求，获取数据
			$.ajax({
				type : "post",
				url : "${PATH}/role/loadData",
				data : json,
				beforeSend : function() {
					index = layer.load(0, {
						time : 10 * 1000
					});
					return true;
				},
				success : function(result) {
					//console.log(result);
					layer.close(index);
					buildTableContent(result);
					buildPageNav(result);
				}
			});
		}

		//展示数据
		function buildTableContent(result) {
			//console.log("initShow"+result);
			//清除原有数据
			$("#contentTable tbody").empty();
			var roleList = result.list;
			//var content = '';
			$.each(
				roleList,
				function(i, e) {
					/*
					content+='<tr>';
					content+='  <td>'+ (i+1) +'</td>';
					content+='  <td><input type="checkbox"></td>';
					content+='  <td>'+ e.name +'</td>';
					content+='  <td>';
					content+='	  <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>';
					content+='	  <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button>';
					content+='	  <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button>';
					content+='  </td>';
					content+='</tr>';
					 */
					var tr = $('<tr></tr>');
					tr.append('  <td>' + (i + 1) + '</td>');
					tr.append('  <td><input type="checkbox"></td>');
					tr.append('  <td>' + e.name + '</td>');

					var td = $('<td></td>');
					td.append('	  <button type="button" class="btn btn-success btn-xs" onclick="assignPermission('+e.id+')"><i class=" glyphicon glyphicon-check"></i></button>');
					td.append('	  <button type="button" class="btn btn-primary btn-xs" onclick="updateRole('+e.id+')"><i class=" glyphicon glyphicon-pencil"></i></button>');
					td.append('	  <button type="button" class="btn btn-danger btn-xs" onclick="deleteRole('+e.id+')"><i class=" glyphicon glyphicon-remove"></i></button>');

					tr.append(td);

					$("#contentTable tbody").append(tr);
				});
			//$("tbody").html(content);
		}

		//构建分页条
		function buildPageNav(nav) {
			$("ul.pagination").empty();
			var firstPage = "<li pn='1'><a onclick='initData(1)'>首页</a></li>";
			var prePage = "";
			var nextPage = "";
			var lastPage = "<li pn='"+nav.pages+"'><a onclick='initData("
					+ nav.pages + ")'>末页</a></li>";
			$("ul.pagination").append(firstPage);
			//上一页判断
			if (nav.hasPreviousPage) {
				prePage = "<li pn='"+nav.prePage+"'><a onclick='initData("
						+ nav.prePage + ")'>上一页</a></li>";
			} else {
				prePage = "<li class='disabled'><a href='#'>上一页</a></li>";
			}
			$("ul.pagination").append(prePage);

			//中间的连续分页
			$.each(nav.navigatepageNums, function() {
				//判断正在遍历的页码，是否当前页，如果是高亮显示
				var cur = "";
				if (this == nav.pageNum) { //是当前页
					cur = "<li pn='"+this+"' class='active'><a href='#'>"
							+ this + "</a></li>";
				} else {
					cur = "<li pn='"+this+"'><a onclick='initData(" + this
							+ ")'>" + this + "</a></li>";
				}
				$("ul.pagination").append(cur);
			});
			//下一页判断
			if (nav.hasNextPage) {
				nextPage = "<li pn='"+nav.nextPage+"'><a onclick='initData("
						+ nav.nextPage + ")'>下一页</a></li>";
			} else {
				nextPage = "<li class='disabled'><a href='#'>下一页</a></li>";
			}
			$("ul.pagination").append(nextPage);
			$("ul.pagination").append(lastPage);
		}

		$("#queryBtn").click(function() {
			var condition = $("#condition").val();
			json.condition = condition;
			initData(1);
		});
		
		//===========添加开始==========================================
		function showAddModal() {
			$("#addModal").modal({
				show: true,
				backdrop: 'static'
			});
		}
		
		$("#saveBtn").click(function() {
			var name = $("#addModal input[name='name']").val();
			$.ajax({
				type: "post",
				url: "${PATH}/role/doAdd",
				data: {
					name: name
				},
				beforeSend: function() {
					return true;
				},
				success: function(result) {
					if("ok"==result){
						layer.msg("添加成功",{time:1000},function() {
							$("#addModal").modal('hide');
							$("#addModal input[name='name']").val("");
							initData(1);
						});
					}else if("403"==result){
						layer.msg("添加失败,权限不足");
					}else{
						layer.msg("添加失败");
					}
				},
				error: function() {
					layer.msg("添加失败,无法连接到服务器");
				}
			});
		});
		//===========添加结束==========================================
		
		//===========修改开始==========================================
		
		
		/* $(".updateClass").click(function() {
			alert("update");
		}); */
		/* $("#contentTable tbody").on('click','.updateClass',function(){
			alert("update");
		}); */
		function updateRole(roleId) {
			$.get(
				"${PATH}/role/getRoleById",
				{
					roleId: roleId
				},
	          	function(data){
					//console.log(data);
					$("#updateModal").modal({
						show: true,
						backdrop: 'static'
					});
					$("#updateModal input[name='name']").val(data.name);
					$("#updateModal input[name='id']").val(data.id);
	          	}
			);
		}
		
		$("#updateBtn").click(function() {
			var name = $("#updateModal input[name='name']").val();
			var id = $("#updateModal input[name='id']").val();
			$.ajax({
				type: "post",
				url: "${PATH}/role/doUpdate",
				data: {
					id: id,
					name: name
				},
				beforeSend: function() {
					return true;
				},
				success: function(result) {
					if("ok"==result){
						layer.msg("修改成功",{time:1000},function() {
							$("#updateModal").modal('hide');
							$("#updateModal input[name='name']").val("");
							$("#updateModal input[name='id']").val("");
							initData(json.pageNum);
							
						});
					}else{
						layer.msg("修改失败");
					}
				},
				error: function() {
					layer.msg("修改失败,无法连接到服务器");
				}
			});
		});
		
		//===========修改结束==========================================
			
		//===========删除开始==========================================
		function deleteRole(roleId) {
			layer.confirm("您确定要删除吗?",
				{
					btn: ["确定","取消"]
				},
				function(index) {
					$.post("${PATH}/role/doDelete", 
					  { roleId: roleId },
			          function(data){
						if("ok"==data){
							layer.msg("删除成功",{time:1000},function() {
								initData(json.pageNum);
								
							});
						}else{
							layer.msg("删除失败");
						}
			          }
					);
					layer.close(index);
				},
				function(index) {
					layer.close(index);
				}
			);
			
		}
		//===========删除结束==========================================
		
		//===========给角色分配权限 开始==========================================

		var assignRoleId = '';
			
		function assignPermission(roleId) {
			$("#assignModal").modal({
				show: true,
				backdrop: 'static'
			});
			assignRoleId = roleId;
			initTree();
		}
		
		function initTree(){
			var setting = {
					data: {
						simpleData: {
							enable: true,
							pIdKey: "pid"
						},
						key: {
							url: "xUrl",
							name:"title"
						}
					},
					view: {
						addDiyDom: addDiyDom
					},
					check: {
						enable: true
					}
			};
			//加载数据
			$.get("${PATH}/permission/listAllPermissionTree",function(data){			
				//data.push({"id":0,"title":"系统权限","icon":"glyphicon glyphicon-asterisk"});
				
				var tree = $.fn.zTree.init($("#treeDemo"), setting, data);
				var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
				treeObj.expandAll(true);
				
				//回显数据,已分配许可
				$.get("${PATH}/role/listPermissionIdByRoleId", {
					roleId:assignRoleId
				},function(data){	
					var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
					$.each(data,function(i,e){
						var permissionId = e;
						var node = treeObj.getNodeByParam("id",permissionId,null);
						treeObj.checkNode(node, true, false, false);
					});
				});
			});
		}
		
		
		function addDiyDom(treeId,treeNode){
			$("#"+treeNode.tId+"_ico").removeClass();
			$("#"+treeNode.tId+"_span").before('<span class="'+treeNode.icon+'"></span>');
		}
		
		$("#assignBtn").click(function() {
			var json = {
					roleId: assignRoleId
			};
			console.log(assignRoleId);
			var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
			var nodes = treeObj.getCheckedNodes(true);
			$.each(nodes,function(i,e){
				var permissionId = e.id;
				console.log(permissionId);
				json['ids['+i+']'] = permissionId;
			});
			
			$.ajax({
				type: "post",
				url: "${PATH}/role/doAssignPermissionToRole",
				data: json,
				success: function(result){
					if("ok"==result){
    					layer.msg("分配成功",{time:1000},function(){
    						$("#assignModal").modal('hide');
    					});
    				}else{
    					layer.msg("分配失败");
    				}
				}
			});
		});
		
		//===========给角色分配权限 结束==========================================
	</script>
</body>
</html>
